<template>
  <div>
    <basic-container>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>首页</el-breadcrumb-item>
        <el-breadcrumb-item 
          :to="{path:'/ad/ad_id_config?pageNum='+pageNum}"
          
        >广告位id配置</el-breadcrumb-item>
        <el-breadcrumb-item>编辑</el-breadcrumb-item>
      </el-breadcrumb>
    </basic-container>
    <basic-container>
      <avue-form
        v-model="form"
        :option="option"
        style="width: 66%; margin-left: 10%"
        @submit="submit"
        ref="formName"
      >
        <template slot="adpeople">
          <div>
            <!-- {{checked}} -->
            <!-- {{gys}} -->
            <el-checkbox-group v-model="checked">
              <div v-for="(e, i) in gys" :key="i" id="a1">
                <el-row>
                  <el-col :span="8">
                    <el-checkbox :label="e">{{
                      e.ad_provider_name
                    }}</el-checkbox>
                  </el-col>
                  <el-col :span="8">
                    曝光次数 :
                    <el-input
                    type="number"
                      placeholder="曝光次数"
                      v-model="e.num"
                      style="width: 40 !important"
                    />
                    次&nbsp;&nbsp;
                  </el-col>

                  <el-col :span="8">
                    排序 :
                    <el-input
                    type="number"
                      placeholder="排序"
                      v-model="e.sort"
                      style="width: 40 !important"
                    />
                  </el-col>
                </el-row>
              </div>
            </el-checkbox-group>
          </div>
        </template>
      </avue-form>
    </basic-container>
  </div>
</template>
<script>
import {
  getAdProvider,
  getAdPositionList,
  updateConfigAd,
  getConfigAdById,
} from "@/api/cat/ad";
import { catUrl } from "@/config/env";
import { uploadFile,selectVersion} from "@/api/cat/baseUrls";
export default {
  async created() {
    this.ad_id = this.$route.query.ad_id;
    this.pageNum = this.$route.query.pageNum;

    let response = await getAdPositionList();
    this.option.column[2].dicData = response.data.source;
    //根据id查询广告数据
    this.$nextTick(async () => {
      let { data } = await getConfigAdById(this.ad_id);
      data.source.ad_position_id = parseInt(data.source.ad_position_id);
      this.form = data.source;
    });
  },
  methods: {
    getExecStrs (str) {
        var reg =/("\d{1,3}":)/g
        var list = []
        var result = null
        do {
            result = reg.exec(str)
            result && list.push(result[1])
        } while (result)
        return list
    },
    async submit(row,loading) { 
          this.checked.sort((e,e2) => (e.sort==undefined?0:Number(e.sort)) - (e2.sort==undefined?0:Number(e2.sort)));
          let key = false;
          let str = "{";
          this.checked.forEach((item, index) => {
            if(item.num==undefined||item.num==0){
              key = true;
            }
            // debugger
            if (item.sort == undefined || isNaN(item.sort)) {
              this.$set(this.checked[index], "sort", 0);
            }
            if(item.num == undefined||isNaN(item.num)){
              this.$set(this.checked[index], "num", 0);
            }
            str += `"${item.ad_type}":{"sort":"${item.sort}","name":"${item.ad_provider_name}","ad_type":"${item.ad_type}","exposure":"${Number(item.num)}","ad_position":"${item.position_id}","ad_position_id":"${item.ad_provider_id}"}`
            // str += `"${item.ad_type}":{"name":"${item.ad_provider_name}","ad_type":"${item.ad_type}","exposure":"${item.num}","ad_position":"${item.position_id}","ad_position_id":"${item.ad_provider_id}"}`;
            if (index != this.checked.length - 1) {
              str += ",";
            }
          });
          if(key){
            loading();
            return this.$message.error("曝光次数必须大于0");
          }
          str += "}";
          if(str=="{}"){
            //没有勾选广告供应商
        //校验自定义广告位名称-广告位描述-活动图-跳转路径是否填写,必须填写,没有填写提示填写
        //description title ad_image_url ad_image_jump

        if((this.form.title==''||this.form.title==undefined)
          &&(this.form.description==''||this.form.description==undefined)
          &&(this.form.ad_image_url==''||this.form.ad_image_url==undefined)
          &&(this.form.ad_image_jump==''||this.form.ad_image_jump==undefined)){
              loading();
              return this.$message.error("广告供应商或广告位名称必须填有一项!")
            }
            if(this.form.title==''||this.form.title==undefined){
              loading();
              return this.$message.error("未勾选广告供应商,请填写广告位名称");
            }
            if(this.form.description==''||this.form.description==undefined){
              loading();
              return this.$message.error("未勾选广告供应商,请填写广告位描述");
            }
            if(this.form.ad_image_url==''||this.form.ad_image_url==undefined){
              loading();
              return this.$message.error("未勾选广告供应商,请上传活动图");
            }
            if(this.form.ad_image_jump==''||this.form.ad_image_jump==undefined){
              loading();
              return this.$message.error("未勾选广告供应商,请填写跳转路径");
            }
          }
          //判断是否选择了图文广告,如果选择了图文,必须输入内容
          if(str.indexOf('"ad_type":"3"') != -1){
            //选择了图文,判断是否输入了内容
            if((this.form.title==''||this.form.title==undefined)
            ||(this.form.description==''||this.form.description==undefined)
            ||(this.form.ad_image_url==''||this.form.ad_image_url==undefined)
            ||(this.form.ad_image_jump==''||this.form.ad_image_jump==undefined)){
              loading()
              return this.$message.error("勾选了图文广告,必须填写(广告位名称、广告位描述、跳转路径、活动图)")
            }
          }
          this.form.ad_type = str;
          // debugger
          if(this.form.second_ad_type!=undefined){
            let se = this.second.filter(item => item.ad_type == this.form.second_ad_type)[0];
            if(se!=undefined){
              this.form.second_ad_position_id = se.ad_provider_id;
              this.form.second_ad_type = se.ad_type;
            }
          }
          if(this.form.third_ad_type!=undefined){
            let th = this.third.filter(item => item.ad_type == this.form.third_ad_type)[0];    
            if(th!=undefined){
              this.form.third_ad_position_id = th.ad_provider_id;
              this.form.third_ad_type = th.ad_type;
            }
          }
          // loading()
          // return
          delete this.form.$ad_position_id;
          delete this.form.$app_id;
          delete this.form.$is_close;
          delete this.form.$second_ad_type;
          delete this.form.$third_ad_type;
          delete this.form.$version_name;
          this.form.ad_image_url = this.form.ad_image_url==undefined?"":this.form.ad_image_url;
          this.form.description = this.form.description==undefined?"":this.form.description;
          this.form.title = this.form.title==undefined?"":this.form.title;
          this.form.ad_image_jump = this.form.ad_image_jump==undefined?"":this.form.ad_image_jump;
          this.form.second_ad_position_id = this.form.second_ad_position_id==undefined?"":this.form.second_ad_position_id;
          this.form.third_ad_position_id = this.form.third_ad_position_id==undefined?"":this.form.third_ad_position_id;
          let { data } = await updateConfigAd(this.form);
          if (data.code == 1) { 
            this.$router.push("/ad/ad_id_config");
          } else {
            loading();
          }
    },
  },
  data() {
    return {
      ad_id: "",
      pageNum:1,
      second:[],
      third:[],
      checked: [],
      form: {},
      gys: [],
      option: {
        column: [
          {
            type: "select",
            label: "App名称",
            span: 24,
            display: true,
            prop: "app_id",
            readonly: true,
            disabled: true,
            value: "61096114",
            dicData: [
              {
                label: "橘子猫轻小说",
                value: "61096114",
              },
            ],
          },
          {
            label: "版本号",
            prop: "version_name",
            type: "select",
            search: true,
            placeholder: "请输入版本号",
            dicUrl: `${catUrl}/${selectVersion.selectVersion}`,
            props: {
              label: "app_version",
              value: "app_version",
            },
            dicFormatter: (res) => {
              return res.source;
            },
            rules: [
              {
                required: true,
                message: "版本号必须填写",
              },
            ],
          },
          {
            type: "select",
            label: "广告位置名称",
            // dicUrl:`${ddUrl}/adoperation/getAdPositionList`,
            span: 24,
            dicData: [],
            props: {
              label: "advertiser_type",
              value: "id",
            },
            display : true,
            required: true,
            rules: [
              {
                required: true,
                message: "广告位置名称必须填写",
              },
            ],
            pattern: "\\.+",
            // value:1,
            // dicFlag:true,
            prop: "ad_position_id",
            change: async (value) => {
              if (value.value != "") {
                let response = await getAdProvider(value.value, 0);
                this.gys = response.data.source;
                this.gys.push({
                  ad_provider_id: value.value,
                  ad_provider_name: "图文广告",
                  ad_type: 3,
                  position_id: value.value
                })
                if (this.ad_id) {
                  let { data } = await getConfigAdById(this.ad_id);
                  let ad_type = JSON.parse(data.source.ad_type);
                  // let l = this.getExecStrs(data.source.ad_type).map(e=>e.replace(":",'').replace(/"/g,''))
                  // let x = [];

                  // l.forEach(e=>{
                  //   alert(e)
                  //     for(let key in ad_type){
                  //   if(e==key){
                  //     x.push(ad_type[key])
                  //   }
                  // }
                  // })
                  
                  // this.x.sort((e,e2) => (e.sort==undefined?0:Number(e.sort)) - (e2.sort==undefined?0:Number(e2.sort)));
                  // let num = 1;
                  // x.forEach(item =>{
                  //   let data = item
                  //   this.gys.forEach((e,index) =>{
                  //     if (item.ad_provider_name == data.name) {
                  //       this.$set(this.gys[index], "sort", num++);
                  //       this.$set(this.gys[index], "num", data.exposure);
                  //       this.checked.push(item);
                  //     }
                  //   })
                  // })

                  // debugger;
                  // let num = 1;
                  for (let key in ad_type) {
                    let data = ad_type[key];
                    this.gys.forEach((item, index) => {
                      if (item.ad_provider_name == data.name) {
                        // item.sort = data.ad_type
                        // item.num = data.exposure
                        // this.$set(this.gys,index,item)
                        this.$set(this.gys[index], "sort", Number(data.sort));
                        this.$set(this.gys[index], "num", data.exposure);
                        this.checked.push(item);
                      }
                    });
                  }
                  this.ad_id = null;
                  // console.info('data', this.checked)
                  // debugger
                }
                response = await getAdProvider(value.value, 1);
                this.second = response.data.source;
                this.option.column[4].dicData = response.data.source;

                response = await getAdProvider(value.value, 2);
                this.third = response.data.source;
                this.option.column[5].dicData = response.data.source;
              }
            },
          },
          {
            type: "input",
            label: "广告供应商",
            span: 24,
            display: true,
            prop: "adpeople",
            formslot: true
          },
          {
            type: "select",
            label: "保底广告供应商1",
            span: 24,
            dicData: [],
            display : true,
            required: true,
            props: {
              label: "ad_provider_name",
              value: "ad_type",
            },
            prop: "second_ad_type",
          },
          {
            type: "select",
            label: "保底广告供应商2",
            span: 24,
            dicData: [],
            display : true,
            required: true,
            props: {
              label: "ad_provider_name",
              value: "ad_type",
            },
            prop: "third_ad_type",
          },
          {
            type: "input",
            label: "广告位名称",
            span: 24,
            prop: "title",
            required: true,
          },
          {
            type: "input",
            label: "广告位描述",
            span: 24,
            prop: "description",
            required: true,
          },
          {
            type: "upload",
            label: "活动图",
            span: 24,
            display: true,
            showFileList: true,
            limit: 10,
            propsHttp: {},
            canvasOption: {},
            prop: "ad_image_url",
            drag: false,
            listType: "picture-img",
            action: `${catUrl}${uploadFile.uploadFile}`,
            propsHttp: {
              url: "source",
            }
          },
          {
            type: "input",
            label: "跳转地址",
            span: 24,
            display: true,
            prop: "ad_image_jump",
          },
          {
            type: "select",
            label: "状态",
            dicData: [
              {
                label: "开启",
                value: 0,
              },
              {
                label: "关闭",
                value: 1,
              },
            ],
            required: true,
            rules: [
              {
                required: true,
                message: "状态必须选择",
              },
            ],
            pattern: "\\.+",
            cascaderItem: [],
            span: 24,
            display: true,
            props: {
              label: "label",
              value: "value",
            },
            prop: "is_close",
          },
        ],
        labelPosition: "right",
        labelSuffix: "：",
        labelWidth: 150,
        gutter: 0,
        menuBtn: true,
        submitBtn: true,
        submitText: "提交",
        emptyBtn: true,
        emptyText: "清空",
        menuPosition: "center",
      },
    };
  },
};
</script>

